package com.campus.client.view;

import com.campus.client.controller.StudentAccountManagementController;
import com.campus.client.net.ClientConnector;
import com.campus.common.vo.AcademicRecord;
import com.campus.common.vo.Student;
import com.campus.common.vo.User;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Callback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class StudentAccountManagementFrame {
    private StudentAccountManagementController studentController;
    private TableView<Student> studentTable;
    private MenuBar menuBar;
    private Button backBtn;
    private User user = new User();
    private Button processRequestsBtn;

    private MenuItem dealRequests;

    public User getUser() {
        return user;
    }

    public void setUser(String Id, String password, String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
    }

    public void start(Stage primaryStage) throws Exception {
        studentController = new StudentAccountManagementController(new ClientConnector("172.20.10.2", 8888));

        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.getStyleClass().add("main-container");

        // 顶部标题栏
        HBox headerBox = new HBox();
        headerBox.getStyleClass().add("header-box");
        headerBox.setAlignment(Pos.CENTER_LEFT);
        headerBox.setPadding(new Insets(10, 15, 10, 15));

        Label titleLabel = new Label("学生账号管理 - 管理员版");
        titleLabel.getStyleClass().add("header-title");

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        // 创建菜单栏
        menuBar = createMenuBar();

        Region buttonSpacer = new Region();
        buttonSpacer.setPrefWidth(10);

        backBtn = createStyledButton("返回");
        backBtn.getStyleClass().add("secondary-button");
        backBtn.setOnAction(e -> back());

        headerBox.getChildren().addAll(titleLabel, spacer, menuBar, buttonSpacer, backBtn);
        root.setTop(headerBox);

        // 内容区域
        VBox contentBox = new VBox();
        contentBox.getStyleClass().add("content-box");
        contentBox.setPadding(new Insets(15));

        // 添加搜索面板
        HBox searchPanel = createSearchPanel();
        contentBox.getChildren().add(searchPanel);

        // 创建表格
        studentTable = new TableView<>();
        studentTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        setupTableColumns();

        // 添加表格到滚动面板
        ScrollPane scrollPane = new ScrollPane(studentTable);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        scrollPane.getStyleClass().add("scroll-pane");

        contentBox.getChildren().add(scrollPane);
        root.setCenter(contentBox);

        HBox bottomBox = new HBox();
        bottomBox.setAlignment(Pos.BOTTOM_RIGHT);
        bottomBox.setPadding(new Insets(10, 0, 10, 0));

        processRequestsBtn = createStyledButton("处理请求");
        processRequestsBtn.getStyleClass().add("primary-button");
        processRequestsBtn.setOnAction(e -> {
            try {
                showStudentApprovalFrame();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });

        bottomBox.getChildren().add(processRequestsBtn);
        root.setBottom(bottomBox);

        // 默认加载所有学生
        loadAllStudents();

        Scene scene = new Scene(root, 1200, 700);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        primaryStage.setTitle("学生账号管理 - 管理员版");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // 创建菜单栏
    private MenuBar createMenuBar() {
        MenuBar menuBar = new MenuBar();
        menuBar.getStyleClass().add("student-menu-bar");

        Menu viewMenu = new Menu("显示操作");
        MenuItem allStudentsItem = new MenuItem("显示所有学生");
        allStudentsItem.setOnAction(e -> loadAllStudents());

        Menu manageMenu = new Menu("管理");
        MenuItem addStudentItem = new MenuItem("新增学生");
        addStudentItem.setOnAction(e -> showAddStudentDialog());

        viewMenu.getItems().add(allStudentsItem);
        manageMenu.getItems().add(addStudentItem);

        menuBar.getMenus().addAll(viewMenu, manageMenu);
        return menuBar;
    }

    // 创建搜索面板
    private HBox createSearchPanel() {
        HBox searchPanel = new HBox(10);
        searchPanel.setPadding(new Insets(10));
        searchPanel.setAlignment(Pos.CENTER_LEFT);

        TextField searchField = new TextField();
        searchField.setPromptText("输入姓名或学号");
        searchField.setPrefWidth(200);

        Button searchButton = createStyledButton("搜索");
        searchButton.setOnAction(e -> {
            String keyword = searchField.getText().trim();
            if (!keyword.isEmpty()) {
                try {
                    List<Student> studentsByName = studentController.searchStudentsByName(keyword);
                    List<Student> studentsById = studentController.searchStudentsById(keyword);

                    // 合并结果，去重
                    List<Student> resultList = new ArrayList<>();
                    resultList.addAll(studentsByName);
                    resultList.addAll(studentsById);

                    // 去重
                    for (int i = 0; i < resultList.size(); i++) {
                        for (int j = i + 1; j < resultList.size(); j++) {
                            if (resultList.get(i).getStudentId().equals(resultList.get(j).getStudentId())) {
                                resultList.remove(j);
                                j--;
                            }
                        }
                    }

                    displaySearchResults(resultList, keyword);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    showAlert("错误", "搜索失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                }
            }
        });

        Button clearButton = createStyledButton("清除搜索");
        clearButton.setOnAction(e -> {
            searchField.clear();
            loadAllStudents();
        });

        searchPanel.getChildren().addAll(
                new Label("搜索:"), searchField, searchButton, clearButton
        );

        return searchPanel;
    }

    // 设置表格列
    private void setupTableColumns() {
        // 学号列
        TableColumn<Student, String> idCol = new TableColumn<>("学号");
        idCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getStudentId()));
        idCol.setMinWidth(100);

        // 姓名列
        TableColumn<Student, String> nameCol = new TableColumn<>("姓名");
        nameCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getStudentName()));
        nameCol.setMinWidth(80);

        // 年龄列
        TableColumn<Student, String> ageCol = new TableColumn<>("年龄");
        ageCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                String.valueOf(cellData.getValue().getAcademicRecord().getAge())));
        ageCol.setMinWidth(60);

        // 性别列
        TableColumn<Student, String> sexCol = new TableColumn<>("性别");
        sexCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                cellData.getValue().getAcademicRecord().getSex()));
        sexCol.setMinWidth(60);

        // 年级列
        TableColumn<Student, String> gradeCol = new TableColumn<>("年级");
        gradeCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                cellData.getValue().getAcademicRecord().getGrade()));
        gradeCol.setMinWidth(80);

        // 班级列
        TableColumn<Student, String> classCol = new TableColumn<>("班级");
        classCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                cellData.getValue().getAcademicRecord().getClassName()));
        classCol.setMinWidth(80);

        // 专业列
        TableColumn<Student, String> majorCol = new TableColumn<>("专业");
        majorCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                cellData.getValue().getAcademicRecord().getMajor()));
        majorCol.setMinWidth(120);

        // 状态列
        TableColumn<Student, String> statusCol = new TableColumn<>("状态");
        statusCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                cellData.getValue().getAcademicRecord().getStatus()));
        statusCol.setMinWidth(80);

        // 操作列
        TableColumn<Student, Void> actionCol = new TableColumn<>("操作");
        actionCol.setMinWidth(200);
        actionCol.setCellFactory(new Callback<TableColumn<Student, Void>, TableCell<Student, Void>>() {
            @Override
            public TableCell<Student, Void> call(final TableColumn<Student, Void> param) {
                return new TableCell<Student, Void>() {
                    private final Button deleteBtn = createStyledButton("删除");
                    private final Button updateBtn = createStyledButton("修改");
                    private final HBox pane = new HBox(10, deleteBtn, updateBtn);

                    {
                        pane.setAlignment(Pos.CENTER);
                        deleteBtn.getStyleClass().add("danger-button");
                        updateBtn.getStyleClass().add("primary-button");

                        deleteBtn.setOnAction(event -> {
                            Student student = getTableView().getItems().get(getIndex());
                            Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
                            confirmAlert.setTitle("确认删除");
                            confirmAlert.setHeaderText("确定要删除学生 " + student.getStudentName() + " 吗？");
                            confirmAlert.setContentText("此操作不可恢复。");

                            confirmAlert.showAndWait().ifPresent(response -> {
                                if (response == ButtonType.OK) {
                                    try {
                                        Boolean success = studentController.deleteStudent(student.getStudentId());
                                        if (success) {
                                            showAlert("成功", "删除学生成功", Alert.AlertType.INFORMATION);
                                            loadAllStudents();
                                        } else {
                                            showAlert("失败", "删除学生失败", Alert.AlertType.ERROR);
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        showAlert("错误", "删除失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                                    }
                                }
                            });
                        });

                        updateBtn.setOnAction(event -> {
                            Student student = getTableView().getItems().get(getIndex());
                            showUpdateDialog(student);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(pane);
                        }
                    }
                };
            }
        });

        studentTable.getColumns().addAll(idCol, nameCol, ageCol, sexCol, gradeCol, classCol, majorCol, statusCol, actionCol);
    }

    // 加载所有学生
    private void loadAllStudents() {
        try {
            List<Student> students = studentController.getStudents();
            studentTable.getItems().setAll(students);
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载学生数据失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // 显示搜索结果
    private void displaySearchResults(List<Student> students, String keyword) {
        studentTable.getItems().setAll(students);
    }

    // 显示新增学生对话框
    private void showAddStudentDialog() {
        Dialog<Student> dialog = new Dialog<>();
        dialog.setTitle("新增学生");
        dialog.setHeaderText("请输入学生信息");

        // 设置按钮
        ButtonType addButtonType = new ButtonType("添加", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(addButtonType, ButtonType.CANCEL);

        // 创建表单
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField nameField = new TextField();
        nameField.setPromptText("姓名");

        TextField studentIdField = new TextField();
        studentIdField.setPromptText("学号");

        TextField recordIdField = new TextField();
        recordIdField.setPromptText("学籍号");

        Spinner<Integer> ageSpinner = new Spinner<>(1, 100, 18);

        ComboBox<String> sexComboBox = new ComboBox<>();
        sexComboBox.getItems().addAll("男", "女");
        sexComboBox.setValue("男");

        TextField gradeField = new TextField();
        gradeField.setPromptText("年级");

        TextField classNameField = new TextField();
        classNameField.setPromptText("班级");

        TextField majorField = new TextField();
        majorField.setPromptText("专业");

        ComboBox<String> statusComboBox = new ComboBox<>();
        statusComboBox.getItems().addAll("在读", "毕业", "休学", "退学");
        statusComboBox.setValue("在读");

        DatePicker enrollDatePicker = new DatePicker();
        enrollDatePicker.setPromptText("入学日期");

        TextField contactField = new TextField();
        contactField.setPromptText("联系方式");

        grid.add(new Label("姓名:"), 0, 0);
        grid.add(nameField, 1, 0);
        grid.add(new Label("学号:"), 0, 1);
        grid.add(studentIdField, 1, 1);
        grid.add(new Label("档案号:"), 0, 2);
        grid.add(recordIdField, 1, 2);
        grid.add(new Label("年龄:"), 0, 3);
        grid.add(ageSpinner, 1, 3);
        grid.add(new Label("性别:"), 0, 4);
        grid.add(sexComboBox, 1, 4);
        grid.add(new Label("年级:"), 0, 5);
        grid.add(gradeField, 1, 5);
        grid.add(new Label("班级:"), 0, 6);
        grid.add(classNameField, 1, 6);
        grid.add(new Label("专业:"), 0, 7);
        grid.add(majorField, 1, 7);
        grid.add(new Label("状态:"), 0, 8);
        grid.add(statusComboBox, 1, 8);
        grid.add(new Label("入学日期:"), 0, 9);
        grid.add(enrollDatePicker, 1, 9);
        grid.add(new Label("联系方式:"), 0, 10);
        grid.add(contactField, 1, 10);

        dialog.getDialogPane().setContent(grid);

        // 转换结果为Student对象
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == addButtonType) {
                Student newStudent = new Student();
                newStudent.setStudentName(nameField.getText().trim());
                newStudent.setStudentId(studentIdField.getText().trim());
                AcademicRecord newAcademicRecord = new AcademicRecord();
                newAcademicRecord.setRecordId(recordIdField.getText().trim());
                newAcademicRecord.setAge(ageSpinner.getValue());
                newAcademicRecord.setSex(sexComboBox.getValue());
                newAcademicRecord.setGrade(gradeField.getText().trim());
                newAcademicRecord.setClassName(classNameField.getText().trim());
                newAcademicRecord.setMajor(majorField.getText().trim());
                newAcademicRecord.setStatus(statusComboBox.getValue());
                newAcademicRecord.setEnrollDate(enrollDatePicker.getValue().toString());
                newAcademicRecord.setContactInfo(contactField.getText().trim());
                newStudent.setAcademicRecord(newAcademicRecord);
                return newStudent;
            }
            return null;
        });

        Optional<Student> result = dialog.showAndWait();
        result.ifPresent(student -> {
            try {
                Boolean success = studentController.addStudent(student);
                if (success) {
                    showAlert("成功", "新增学生信息成功", Alert.AlertType.INFORMATION);
                    loadAllStudents(); // 刷新列表
                } else {
                    showAlert("失败", "新增学生信息失败", Alert.AlertType.ERROR);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "添加失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });
    }

    // 显示更新学生对话框
    private void showUpdateDialog(Student student) {
        Dialog<Student> dialog = new Dialog<>();
        dialog.setTitle("更新学生信息");
        dialog.setHeaderText("更新学生信息");

        // 设置按钮
        ButtonType updateButtonType = new ButtonType("更新", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(updateButtonType, ButtonType.CANCEL);

        // 创建表单
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField nameField = new TextField(student.getStudentName());
        TextField studentIdField = new TextField(student.getStudentId());
        studentIdField.setEditable(false); // 学号不可编辑
        TextField recordIdField = new TextField(student.getAcademicRecord().getRecordId());

        Spinner<Integer> ageSpinner = new Spinner<>(1, 100, student.getAcademicRecord().getAge());

        ComboBox<String> sexComboBox = new ComboBox<>();
        sexComboBox.getItems().addAll("男", "女");
        sexComboBox.setValue(student.getAcademicRecord().getSex());

        TextField gradeField = new TextField(student.getAcademicRecord().getGrade());
        TextField classNameField = new TextField(student.getAcademicRecord().getClassName());
        TextField majorField = new TextField(student.getAcademicRecord().getMajor());

        ComboBox<String> statusComboBox = new ComboBox<>();
        statusComboBox.getItems().addAll("在读", "毕业", "休学", "退学");
        statusComboBox.setValue(student.getAcademicRecord().getStatus());

        DatePicker enrollDatePicker = new DatePicker();
        if (student.getAcademicRecord().getEnrollDate() != null && !student.getAcademicRecord().getEnrollDate().isEmpty()) {
            enrollDatePicker.setValue(java.time.LocalDate.parse(student.getAcademicRecord().getEnrollDate()));
        }

        TextField contactField = new TextField(student.getAcademicRecord().getContactInfo());

        grid.add(new Label("姓名:"), 0, 0);
        grid.add(nameField, 1, 0);
        grid.add(new Label("学号:"), 0, 1);
        grid.add(studentIdField, 1, 1);
        grid.add(new Label("学籍号:"), 0, 2);
        grid.add(recordIdField, 1, 2);
        grid.add(new Label("年龄:"), 0, 3);
        grid.add(ageSpinner, 1, 3);
        grid.add(new Label("性别:"), 0, 4);
        grid.add(sexComboBox, 1, 4);
        grid.add(new Label("年级:"), 0, 5);
        grid.add(gradeField, 1, 5);
        grid.add(new Label("班级:"), 0, 6);
        grid.add(classNameField, 1, 6);
        grid.add(new Label("专业:"), 0, 7);
        grid.add(majorField, 1, 7);
        grid.add(new Label("状态:"), 0, 8);
        grid.add(statusComboBox, 1, 8);
        grid.add(new Label("入学日期:"), 0, 9);
        grid.add(enrollDatePicker, 1, 9);
        grid.add(new Label("联系方式:"), 0, 10);
        grid.add(contactField, 1, 10);

        dialog.getDialogPane().setContent(grid);

        // 转换结果为Student对象
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == updateButtonType) {
                student.setStudentName(nameField.getText().trim());
                AcademicRecord academicRecord = new AcademicRecord();
                academicRecord.setRecordId(recordIdField.getText().trim());
                academicRecord.setAge(ageSpinner.getValue());
                academicRecord.setSex(sexComboBox.getValue());
                academicRecord.setGrade(gradeField.getText().trim());
                academicRecord.setClassName(classNameField.getText().trim());
                academicRecord.setMajor(majorField.getText().trim());
                academicRecord.setStatus(statusComboBox.getValue());
                academicRecord.setEnrollDate(enrollDatePicker.getValue().toString());
                academicRecord.setContactInfo(contactField.getText().trim());
                student.setAcademicRecord(academicRecord);
                return student;
            }
            return null;
        });

        Optional<Student> result = dialog.showAndWait();
        result.ifPresent(updatedStudent -> {
            try {
                Boolean success = studentController.updateStudent(updatedStudent);
                if (success) {
                    showAlert("成功", "更新学生信息成功", Alert.AlertType.INFORMATION);
                    loadAllStudents(); // 刷新列表
                } else {
                    showAlert("失败", "更新学生信息失败", Alert.AlertType.ERROR);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "更新失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });
    }

    // 统一按钮创建方法
    private Button createStyledButton(String text) {
        Button button = new Button(text);
        button.getStyleClass().add("styled-button");
        return button;
    }

    // 统一提示对话框
    private void showAlert(String title, String message, Alert.AlertType type) {
        Alert alert = new Alert(type, message, ButtonType.OK);
        alert.setHeaderText(title);
        alert.showAndWait();
    }

    private void back() {
        // 获取当前窗口的Stage
        Stage currentStage = (Stage) backBtn.getScene().getWindow();
        currentStage.close();

        // 这里可以添加返回主界面的逻辑
        // 例如：打开管理员主界面
        try {
            AccountManagementFrame accountManagementFrame = new AccountManagementFrame();
            accountManagementFrame.setUser(user.getId(), user.getPassword(), user.getRole());
            accountManagementFrame.start(new Stage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showStudentApprovalFrame() throws Exception {
        // 获取当前登录窗口的Stage
        Stage registerStage = (Stage) processRequestsBtn.getScene().getWindow();

        // 创建主界面
        StudentApprovalFrame studentApprovalFrame = new StudentApprovalFrame();
        studentApprovalFrame.setUser(user.getId(), user.getPassword(),  user.getRole());
        Stage studentApprovalStage = new Stage();

        // 显示主界面
        studentApprovalFrame.start(studentApprovalStage);

        // 关闭登录窗口
        registerStage.close();
    }
}